package com.live.proxy.home;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.Window;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import com.live.proxy.R;
import com.live.proxy.model.UserModel;
import com.live.proxy.sql.UserDatabase;
import com.live.proxy.tool.GetUtil;
import com.live.proxy.tool.OkHttpUtils;
import com.live.proxy.tool.StatusBarUtils;
import com.live.proxy.tool.UpdateChecker;
import com.live.proxy.view.ToastUtils;

import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Response;

public class SettingActivity extends AppCompatActivity {
    ImageButton setting_back;
    RelativeLayout setting_nickname;
    TextView setting_nickname_value;
    TextView setting_pass;
    TextView setting_update;

    UserDatabase userDb;
    UserModel userModel;
    String newPassword = "";
    String newNickname = "";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_setting);
        StatusBarUtils.setDarkStatusWhite(this,R.color.white);
        setting_back = findViewById(R.id.setting_back);
        setting_nickname = findViewById(R.id.setting_nickname);
        setting_nickname_value = findViewById(R.id.setting_nickname_value);
        setting_pass = findViewById(R.id.setting_pass);
        setting_update = findViewById(R.id.setting_update);

        userDb = new UserDatabase(getApplicationContext());
        userModel = userDb.select();
        setting_nickname_value.setText(userModel.getNickname());

        setting_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        setting_nickname.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog_change_nickname();
            }
        });
        setting_pass.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog_change_pass();
            }
        });
        setting_update.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new UpdateChecker(SettingActivity.this,true).checkForUpdates();
            }
        });
    }
    public void dialog_change_pass(){
        final AlertDialog dialog = new AlertDialog.Builder(this).create();
        dialog.setCancelable(false);
        dialog.setView(new EditText(this));
        dialog.show();
        Window window = dialog.getWindow();
        window.setContentView(R.layout.dialog_change_pass);
        final EditText dialog_changepass_old = window.findViewById(R.id.dialog_changepass_old);
        final EditText dialog_changepass_new = window.findViewById(R.id.dialog_changepass_new);
        final EditText dialog_changepass_confirm = window.findViewById(R.id.dialog_changepass_confirm);
        final TextView dialog_changepass_title = window.findViewById(R.id.dialog_changepass_title);
        final TextView dialog_changepass_no = window.findViewById(R.id.dialog_changepass_no);
        final TextView dialog_changepass_ok = window.findViewById(R.id.dialog_changepass_ok);
        dialog_changepass_no.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });
        dialog_changepass_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String oldPass = dialog_changepass_old.getText().toString();
                String newPass = dialog_changepass_new.getText().toString();
                String confirmpPass = dialog_changepass_confirm.getText().toString();
                newPassword = confirmpPass;

                if(oldPass.isEmpty()){
                    dialog_changepass_title.setText("请输入原密码！");
                    return;
                }
                if(newPass.isEmpty()){
                    dialog_changepass_title.setText("请输入新密码！");
                    return;
                }
                if(confirmpPass.isEmpty()){
                    dialog_changepass_title.setText("请输入确认密码！");
                    return;
                }
                if(!confirmpPass.equals(newPass)){
                    dialog_changepass_title.setText("确认密码和新密码不一致！");
                    return;
                }
                try {
                    JSONObject json = new JSONObject();
                    json.put("old_user_password",oldPass);
                    json.put("new_user_password",newPass);
                    getAccount(GetUtil.updatePassword(),json.toString(),userModel.getToken(),1);
                }catch (Exception e){
                    e.printStackTrace();
                }
                dialog.dismiss();
            }
        });
    }
    public void dialog_change_nickname(){
        final AlertDialog dialog = new AlertDialog.Builder(this).create();
        dialog.setCancelable(false);
        dialog.setView(new EditText(this));
        dialog.show();
        Window window = dialog.getWindow();
        window.setContentView(R.layout.dialog_change_nickname);
        final EditText dialog_change_nickname = window.findViewById(R.id.dialog_change_nickname);
        final TextView dialog_change_nickname_no = window.findViewById(R.id.dialog_change_nickname_no);
        final TextView dialog_change_nickname_ok = window.findViewById(R.id.dialog_change_nickname_ok);
        dialog_change_nickname_no.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });
        dialog_change_nickname_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String nickname = dialog_change_nickname.getText().toString();
                newNickname = nickname;
                if(nickname.isEmpty()){
                    ToastUtils.Setinfo(getApplicationContext(),"请输入昵称",2);
                    return;
                }
                try {
                    JSONObject json = new JSONObject();
                    json.put("new_nickname",nickname);
                    getAccount(GetUtil.updateNickname(),json.toString(),userModel.getToken(),2);
                }catch (Exception e){
                    e.printStackTrace();
                }
                dialog.dismiss();
            }
        });
    }
    public static int REQUEST_STATUS = 0;
    public static final int RRQUEST_FAILURE = 1;
    public static final int RRQUEST_SUCCESS = 2;
    @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case RRQUEST_FAILURE:
                    ToastUtils.Setinfo(getApplicationContext(),msg.obj.toString(),2);
                    break;
                case RRQUEST_SUCCESS:
                    try {
                        JSONObject json = new JSONObject(msg.obj.toString());
                        if(json.getInt("code") == 1){
                            switch (REQUEST_STATUS){
                                case 1://更改密码
                                    ToastUtils.Setinfo(getApplicationContext(),json.getString("info"),1);
                                    userDb.updatePass(newPassword);
                                    break;
                                case 2://更改昵称
                                    ToastUtils.Setinfo(getApplicationContext(),json.getString("info"),1);
                                    userDb.updateNickname(newNickname);
                                    setting_nickname_value.setText(newNickname);
                                    break;
                            }
                        }else{
                            ToastUtils.Setinfo(getApplicationContext(),json.getString("info"),2);
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                    break;
            }
        }
    };
    public void getAccount(String url,String jsonStr,String token,int STATUS){
        OkHttpUtils.sendOkHttpJsonTokenRequest(url, jsonStr,new okhttp3.Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Message message = new Message();
                message.what = RRQUEST_FAILURE;
                message.obj = "【请求异常】请联系管理员";
                handler.sendMessage(message);
            }
            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                REQUEST_STATUS = STATUS;
                String responseData = response.body().string();
                Message message = new Message();
                message.what = RRQUEST_SUCCESS;
                message.obj = responseData;
                handler.sendMessage(message);
            }
        },token);
    }
}